import { type Site, siteList, updateSiteSort } from '@/api/SiteApi.ts'
import type { SortParam } from '@/api/types/SortParam.ts'
import { ArrayTool, ObjectTool } from '@es-tool/core'
import { type Ref, ref } from 'vue'


export type PropsType = Readonly<{
    groupId: string
}>

export class SiteList {

    public readonly props: PropsType

    public readonly mainRef: Ref<HTMLElement | null>

    public readonly listIsLoading: Ref<boolean> = ref(false)

    public readonly list: Ref<Array<Site>> = ref([])


    public constructor(props: PropsType, ref: Ref<HTMLElement | null>) {
        this.props = props
        this.mainRef = ref

        this.initList = this.initList.bind(this)
        this.findChanges = this.findChanges.bind(this)

        this.initList()
    }

    public initList() {
        this.listIsLoading.value = true
        siteList(this.props.groupId)
                .then(arr => this.list.value = arr.sort((a, b) => a.sort - b.sort))
                .finally(() => this.listIsLoading.value = false)
    }

    public findChanges() {
        const changes: Array<SortParam> = []

        for (let i = 0; i < this.list.value.length; i++) {
            const site = this.list.value[i]
            if (site.sort === i) {
                continue
            }
            const param = {
                id: site.id!,
                sort: i,
            }
            changes.push(param)
        }

        if (ArrayTool.isEmpty(changes)) {
            return
        }

        updateSiteSort(changes)
                .then(() => {
                    console.debug('排序已保存', ObjectTool.copy(changes))
                    this.initList()
                })
    }

}
